package com.xzmzhp.controller.power;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.xzmzhp.constant.ReturnConstant;
import com.xzmzhp.constant.power.MenuConstant;
import com.xzmzhp.pojo.power.Menu;
import com.xzmzhp.security.LoginUser;
import com.xzmzhp.service.power.MenuService;
import com.xzmzhp.utils.return_tool.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author: 王源(xm)
 * @create: 2021-12-26 15:53
 * @program: ams
 * @description: 菜单前台交互类
 */
@Controller
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 返回树形菜单信息
     * @return 菜单信息
     */
    @GetMapping("/selectRoute")
    @ResponseBody
    public ReturnData selectRoute(Authentication authentication) {
        LoginUser loginUser =  (LoginUser) authentication.getPrincipal();
        //获取数据库信息
        List<Menu> list = menuService.selectRoute(loginUser.getUser().getCompetenceId(), MenuConstant.USE);
        if (CollUtil.isEmpty(list)){
            return ReturnData.error(ReturnConstant.FAIL,"获取菜单信息失败");
        }
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名
        treeNodeConfig.setIdKey("menuId");
        treeNodeConfig.setParentIdKey("parentMenu");
        // 最大递归深度
        treeNodeConfig.setDeep(3);
        treeNodeConfig.setWeightKey("menuId");

        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getMenuId().toString());
                    tree.setParentId(treeNode.getParentMenu().toString());
                    tree.setName(treeNode.getMenuName());
                    tree.setWeight(treeNode.getMenuId().toString());
                    // 扩展属性
                    tree.putExtra("level", treeNode.getMenuLevel());
                    tree.putExtra("route_name", treeNode.getRouteName());
                    tree.putExtra("menu_icon", treeNode.getMenuIcon());
                });
        return ReturnData.ok(treeNodes);
    }
}
